package org.example;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * cpu us使用率高的demo
 */
@RestController
@RequestMapping("/HighSysCpu")
public class HighSysCpuUsageDemo {

    private static int count  = 100;

    private static Object[] locks = new Object[count];

    @GetMapping("/test")
    public void test() {
	
        // 创建多个线程
        for (int i = 0; i < count; i++) {
            Object obj = new Object();
            locks[i] = obj;
            Thread thread = new Thread(new StateSwitchingTask(i));
            thread.start();
        }


    }

    static class StateSwitchingTask implements Runnable {
        private volatile boolean running = true;

        private Object lock;

        Random random = new Random();


        StateSwitchingTask(int i){
            this.lock = locks[i];
        }

        @Override
        public void run() {

            while (true) {
                try{

                    synchronized (lock){
                        lock.wait(random.nextInt(10));
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        private void toggleRunningState() {
            running = !running;
        }

        private void doCpuIntensiveTask() {
            double result = 0.0;
            for (int i = 0; i < 1000000; i++) {
                result += Math.random() * Math.random();
            }
        }
    }
}
